<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" ref="searchForm">
            <!-- <el-form-item prop="remindContent">
              <el-input v-model="searchForm.remindContent" :clearable="true" placeholder="消息内容"></el-input>
            </el-form-item> -->
            <el-form-item prop="msgType" label="消息类型:">
              <el-select v-model="searchForm.msgType" :clearable="true" placeholder="请选择消息类型">
                <el-option v-for="item in msgType" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="msgStatus" label="消息状态:">
              <el-select v-model="searchForm.msgStatus" :clearable="true" placeholder="请选择消息状态">
                <el-option v-for="item in msgStatue" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="date" label="查询日期:">
              <el-date-picker
                v-model="searchForm.date"
                :clearable="true"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="onSearch" style="padding: 7px 18px">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <div>
            <!--<el-button size="mini" type="success" plain icon="el-icon-finished" @click="handleClickScan">扫码</el-button>-->
            <el-button size="mini" type="success" plain icon="el-icon-finished" @click="cleanAllMsg">全部已读</el-button>
            <el-button size="mini" type="info" icon="el-icon-document-checked" plain @click="cleanMsgStatus">已读</el-button>
            <el-button v-has="permissionAdd" type="primary" plain icon="fa fa-plus" @click="handleClickAdd()" size="mini"> 新增</el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <el-table :data="tableList" :fit="true" @selection-change="changeSelect">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="remindType" label="消息类型" width="200">
          <template slot-scope="scope">
            <span v-if="scope.row.remindType == 1"> 系统消息 </span>
            <span v-if="scope.row.remindType == 10"> 报告单消息 </span>
            <span v-if="scope.row.remindType == 20"> 预约消息 </span>
            <span v-if="scope.row.remindType == 30"> 挂号消息 </span>
            <span v-if="scope.row.remindType == 40"> 采样消息 </span>
            <span v-if="scope.row.remindType == 50"> 收样消息 </span>
            <span v-if="scope.row.remindType == 60"> 标本箱消息 </span>
          </template>
        </el-table-column>
        <el-table-column prop="sourceName" label="消息来源" width="250"></el-table-column>
        <el-table-column prop="remindContent" label="消息内容" width="550"></el-table-column>
        <el-table-column prop="createDate" label="消息时间" width="150"></el-table-column>
        <el-table-column prop="isRead" label="消息状态" :formatter="formatIsRead" width="180" align="center"></el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-row>
              <!-- 温控 -->
              <el-button v-if="scope.row.remindType == 4 && userInfo.userRole == 1" @click="handleSearch(scope.row)" size="mini">前往查看</el-button>
              <!-- 报告单操作 -->
              <el-popconfirm
                v-has="permissionUploadPhoto"
                v-if="scope.row.remindType == 1"
                confirm-button-text="批量新增"
                cancel-button-text="单个新增"
                cel-button-type="Primary"
                icon="el-icon-finished"
                title="前往新增报告单:"
                @confirm="handleMoreMsgAction(scope.row)"
                @cancel="handleMsgAction(scope.row)"
              >
                <!--  v-if="scope.row.remindJumpUrl != ''" -->
                <el-button v-has="scope.row.remindJumpUrl" v-if="scope.row.remindType == 1" slot="reference" size="mini">前往处理</el-button>
              </el-popconfirm>

              <el-button v-has="permissionUploadPhoto" v-if="scope.row.remindType == 1" @click="handleUploadPhoto(scope.row)" size="mini">申请单上传</el-button>
              <el-button v-has="permissionUploadPhotoView" v-if="scope.row.remindType == 1" @click="handleViewPhoto(scope.row)" size="mini">查看申请单</el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <el-dialog title="新增消息" :visible.sync="dialogVisible" :center="isCenter" width="400px">
      <el-form :model="messageForm" ref="messageForm">
        <el-form-item label="医院名称" prop="hospitalId" label-width="100px">
          <el-select v-model="messageForm.hospitalId" filterable clearable reserve-keyword :loading="loadingIns" placeholder="请选择医院" :filter-method="listHospital">
            <el-option v-for="item in pickHospitalList" :key="item.label" :label="item.label" :value="item.label"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收样人员" prop="remindUserId" label-width="100px">
          <el-select
            v-model="messageForm.remindUserId"
            filterable
            clearable
            reserve-keyword
            :loading="loadingIns"
            placeholder="请选择收样人员"
            :filter-method="listUser"
            @focus="listUser"
          >
            <el-option v-for="item in pickUserList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item align="center">
          <el-button type="primary" @click="sureMessageClick">保 存</el-button>
          <el-button @click="cancelMessageClick">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 大图浏览 -->
    <el-dialog title="" :visible.sync="dialogVisiblePhoto" :center="isCenter" width="800px" height="700px">
      <div>
        <!-- <img v-for="url in photoList"
             :src="url" style="width: 200px;height: 180px"/>
        <el-popover
        v-for="url in photoList" :key="url"  placement="right" width="600" height="500px"
        trigger="hover" :open-delay="1000">
          <img class="" :src="url" v-min="url" slot="reference"
               style="max-width:300px;max-height:300px; cursor: pointer;" />
          <img style="max-width:900px;max-height:800px;" :src="url" />
        </el-popover> -->
        <el-image v-for="url in photoList" :key="url" style="max-width: 300px; max-height: 300px; cursor: pointer" :src="url" :preview-src-list="photoList"> </el-image>
      </div>
    </el-dialog>

    <uploadFile ref="uploadFile" @uploadFileList="getUploadFileList" :accept="uploadAccept" folder="report"></uploadFile>
  </div>
</template>

<script>
import uploadFile from '@/components/UploadFile';
import HospitalApi from '@/api/institution/hospital';
import MessageApi from '@/api/message/message';
import AuthApi from '@/api/system/auth';
import { getStorage } from '@/utils/auth';
import * as stn from '@/constants/storeName';
import { mapActions } from 'vuex';

export default {
  name: 'MessageManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      userInfo: {}, // 获取当前登陆用户信息
      dialogVisible: false,
      dialogVisiblePhoto: false,
      isCenter: true,
      loadingIns: false,
      isAdd: false,
      searchForm: {
        msgType: '',
        msgStatus: '0',
        remindContent: '',
        date: [],
      },
      pickUserList: [],
      pickHospitalList: [],
      photoList: [],
      messageForm: {
        remindContent: '',
        remindUserId: '',
        hospitalId: '',
        remindType: '',
      },
      uploadAccept: 'all',
      uploadData: {
        uploadType: null,
        uploadFiles: [],
      },
      tableList: [],
      selectIds: [],

      page: {
        pageNo: 1,
        pageSize: 20,
        pageTotal: 0,
      },
      msgType: [
        { label: '系统', value: '1' },
        { label: '报告单', value: '10' },
        { label: '预约', value: '20' },
        { label: '挂号', value: '30' },
        { label: '采样', value: '40' },
        { label: '收样', value: '50' },
        { label: '标本箱', value: '60' },
      ],
      msgStatue: [
        { label: '未读', value: '0' },
        { label: '已读', value: '1' },
      ],
      roleRules: {
        remindUserId: [
          {
            required: true,
            message: '请选择收样员',
            trigger: 'blur',
          },
        ],
        institutionId: [
          {
            required: true,
            message: '请选择医院',
            trigger: 'blur',
          },
        ],
      },
      permissionAdd: 'SYSTEM_MANAGER_MESSAGE_MESSAGE_LIST_ADD',
      permissionUploadPhoto: 'SYSTEM_MANAGER_MESSAGE_MESSAGE_LIST_UPLOAD_PHOTO',
      permissionUploadPhotoView: 'SYSTEM_MANAGER_MESSAGE_MESSAGE_LIST_UPLOAD_PHOTO_VIEW',
    };
  },
  components: {
    uploadFile,
  },
  mounted() {
    this.userInfo = getStorage(stn.USER_INFO);
    this.initDate();
    this.getTableHeight();
    this.listTable();
    this.listHospital();
    window.addEventListener('keydown', this.keyDown);
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    ...mapActions({
      setUnReadCount: 'setUnReadCount',
    }),
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },

    listTable() {
      let data = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        remindType: this.searchForm.msgType,
        isRead: this.searchForm.msgStatus,
      };
      console.log('>>>>>>data', data);
      if (this.searchForm.date && this.searchForm.date.length == 2) {
        data.createDateBegin = this.$Utils.formatDate(this.searchForm.date[0], 'yyyy-MM-dd hh:mm:ss');
        data.createDateEnd = this.$Utils.formatDate(this.searchForm.date[1], 'yyyy-MM-dd hh:mm:ss');
      }
      this.$emit('show-loading', true);
      MessageApi.listRemind(data)
        .then((res) => {
          this.tableList = res.data.list;
          this.page.pageTotal = res.data.total;
          this.$emit('show-loading', false);
          // console.log(res.data.list)
        })
        .catch((error) => {
          console.error(error);
          this.$emit('show-loading', false);
        });
    },
    onSearch() {
      /*if(this.searchForm.date ===null){
          return this.$message.error(message.MSG_CONFIRM_BEGIN_TIME_IS_NULL);
        }*/
      this.page.pageNo = 1;
      this.listTable();
    },
    changeSelect(val) {
      this.selectIds = [];
      for (let i = 0; i < val.length; i++) {
        //console.log(JSON.stringify(val[i]))
        let id = val[i].remindId;
        this.selectIds.push(id);
      }
    },
    formatIsRead(row, column, cellValue) {
      return cellValue == 1 ? '已读' : '未读';
    },
    handleMsgAction(row) {
      this.$router.push({ path: '/report/reportAdd' });
    },
    handleMoreMsgAction(row) {
      // 批量新增
      // console.log("handleMoreMsgAction")
      // console.log(row.remindId)
      // this.$router.push({ path: '/report/reportBatchAdd',query: {  remindId: row.remindId } });
    },
    handleSearch(row) {
      // 跳转到标本箱列表
      // console.log("handleSearch")
      this.$router.push({ path: '/equip/specimenManagement' });
    },
    handleUploadPhoto(row) {
      let _this = this;
      _this.uploadAccept = 'image';
      _this.uploadData.uploadFiles = [];
      _this.uploadData.uploadType = row.remindId;
      _this.$refs.uploadFile.handleCreate();
    },
    handleViewPhoto(row) {
      // 获取申请单图片
      let _this = this;
      //_this.$Utils.clearData(_this.messageForm);
      _this.dialogVisiblePhoto = true;
      MessageApi.getViewPhoto({ remindId: row.remindId })
        .then((res) => {
          _this.photoList = res.data;
        })
        .catch((error) => {
          console.log('ttt--->' + JSON.stringify(error));
        });
    },
    // 产品导入
    getUploadFileList(val) {
      ////debugger
      let _this = this;
      if (!val) {
        _this.$Utils.messageError('请选择图片上传');
        return;
      }
      _this.uploadData.uploadFiles = val;
      MessageApi.addViewPhoto(this.uploadData)
        .then((res) => {
          _this.$Utils.notifySuccess();
        })
        .catch((error) => {
          _this.$Utils.notifyError('上传失败，请稍后重试');
        });
    },
    cleanAllMsg() {
      let _this = this;
      MessageApi.updateMsgRead({ remindIds: '' })
        .then((res) => {
          _this.listTable();
          _this.getMsgStatus();
        })
        .catch((error) => {
          console.error(error);
        });
    },

    getMsgStatus() {
      let _this = this;
      MessageApi.getRemindMinute({})
        .then((res) => {
          //sessionStorage.setItem("unreadCount",res.data.unreadCount);
          this.setUnReadCount(res.data.unreadCount);
          if (res.data.unreadCount > 0) {
            // console.log("有新消息")
          } else {
            _this.$emit('clear-msg-dot');
          }
        })
        .catch((error) => {
          console.log('ttt--->' + JSON.stringify(error));
        });
    },

    listHospital() {
      let _this = this;
      _this.loadingIns = true;
      let cond = {
        hospitalType: 1,
      };
      HospitalApi.getHospitalNameList(cond)
        .then((res) => {
          setTimeout(() => {
            _this.loadingIns = false;
            _this.pickHospitalList = res.data.map((item) => {
              return {
                value: item.hospitalId,
                label: item.hospitalName,
              };
            });
          }, 200);
        })
        .catch((error) => {
          _this.pickHospitalList = [];
          console.error(error);
        });
    },
    listUser() {
      let _this = this;
      _this.loadingIns = true;
      let cond = {
        roleId: 4,
      };
      AuthApi.listAdminByRole(cond)
        .then((res) => {
          setTimeout(() => {
            _this.loadingIns = false;
            _this.pickUserList = res.data.map((item) => {
              return {
                value: item.userId,
                label: item.userName,
              };
            });
          }, 200);
        })
        .catch((error) => {
          _this.pickUserList = [];
          console.error(error);
        });
    },
    /*handleClickScan(){
        this.$router.push('/message/scanOne')
      },*/
    handleClickAdd() {
      let _this = this;
      _this.$Utils.clearData(_this.messageForm);
      _this.dialogVisible = true;
      _this.isAdd = false;
    },
    sureMessageClick() {
      let _this = this;
      _this.$refs.messageForm.validate((valid) => {
        if (valid) {
          _this.addMessage();
          _this.listTable();
        }
      });
    },
    addMessage() {
      let _this = this;
      let remindContent = '【' + _this.messageForm.hospitalId + '】有新样本需要收取，请尽快处理';
      _this.messageForm.remindContent = remindContent;
      _this.messageForm.remindType = 1;
      MessageApi.addRemindMsg(this.messageForm).then((data) => {
        this.dialogVisible = false;
        _this.$Utils.notifySuccess();
      });
    },
    cancelMessageClick() {
      this.dialogVisible = false;
      //this.$refs.messageForm.resetFields();
    },
    cleanMsgStatus() {
      if (this.selectIds.length > 0) {
        let ids = '';
        for (let i = 0; i < this.selectIds.length; i++) {
          ids += this.selectIds[i] + ',';
        }
        ids = ids.substring(0, ids.length - 1);
        let _this = this;
        MessageApi.updateMsgRead({ remindIds: ids }).then((res) => {
          _this.getMsgStatus();
          _this.listTable();
        });
      } else {
        this.$Utils.notifyError('请选择对应消息');
      }
    },


    initDate() {
      let begin = new Date();
      let nowYear = begin.getFullYear();
      begin.setFullYear(nowYear, 0, 1);
      begin.setHours(0);
      begin.setMinutes(0);
      begin.setSeconds(0);
      // begin.setDate(1);
      let end = new Date();
      end.setHours(23);
      end.setMinutes(59);
      end.setSeconds(59);
      this.searchForm.date = [begin, end];
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listTable();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listTable();
    },
    formatMsgStatus(row, column, cellValue) {
      if (cellValue == -1) {
        return '全部';
      } else if (cellValue == 0) {
        return '未读';
      } else if (cellValue == 1) {
        return '已读';
      }
    },
  },
};
</script>

<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
